package com.tutu.service.impl;

import com.tutu.controller.CommonsController;
import com.tutu.controller.backend.UserController;
import com.tutu.core.Constant;
import com.tutu.core.api.*;
import com.tutu.entity.vo.BaseVo;
import com.tutu.entity.vo.weixin.WxUser;
import com.tutu.service.UserService;
import com.tutu.utils.BaseUtil;
import com.tutu.utils.HttpRequestUtil;
import com.tutu.utils.JsonUtil;
import com.tutu.utils.UnicodeUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * UserServiceImpl
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Override
    public Map<String, Object> pageByParams(Integer companyId, String keyWord, Integer pageNum, Integer pageSize) {
        Map<String, Object> result = HttpRequestUtil.getOnlyData(UserApiUrls.base_prefix + UserApiUrls.page, "keyWord=" + UnicodeUtil.unicodeEncode(keyWord) + "&pageNum=" + pageNum + "&pageSize=" + pageSize + (null != companyId && companyId > 0 ? "&companyId=" + companyId : ""));

        JSONArray content = new JSONArray();
        Map<String, Object> map;

        for (Object o : JSONArray.fromObject(result.get("content"))) {
            map = JsonUtil.json2Map(o);

            map.put("companyName", getCompanyName(map.get("id")));

            content.add(map);
        }

        result.put("content", content);

        return result;
    }

    @Override
    public Map<String, Object> pageByChildParams(Integer companyId, Integer userId, Integer pageNum, Integer pageSize) {
        return HttpRequestUtil.getOnlyData(DeviceUserApiUrls.base_prefix + DeviceUserApiUrls.findDeviceUserTempList, "pageNum=" + pageNum + "&pageSize=" + pageSize + "&userId=" + userId + "&companyId=" + companyId);
    }

    @Override
    public Map<String, Object> getInfoById(Integer id) {
        for (Map<String, Object> map : CommonsController.baseUserList)
            if (map.get("id").equals(id)) return changeUserInfo(map);

        return new HashMap<>();
    }

    public static Map<String, Object> getInfoByOpenId(String openId) {
        for (Map<String, Object> map : CommonsController.baseUserList)
            if (map.get("openId").equals(openId)) return changeUserInfo(map);

        return new HashMap<>();
    }

    static Map<String, Object> changeUserInfo(Map<String, Object> map) {
        map.put("companyList", UserController.tempUserCompanyMap.getOrDefault(map.get("id") + "", ""));

        return map;
    }

    @Override
    public Map<String, Object> saveInfo(HttpServletRequest request, Integer id, String openId, String unionId, String nickName, String name, String mobile, String avatar, String description) {
        LogInfoServiceImpl.saveLogInfo(request, "编辑用户信息，ID：" + id + "，OpenId：" + openId + "，昵称：" + nickName + "，姓名：" + name + "，联系方式：" + mobile + "，头像：" + avatar + "，描述信息：" + description);

        Map<String, Object> map = HttpRequestUtil.getCompleteData(UserApiUrls.base_prefix + UserApiUrls.update, "id=" + id + (BaseUtil.isNotBlank(openId) ? "&openId=" + openId : "") + (BaseUtil.isNotBlank(description) ? "&description=" + UnicodeUtil.unicodeEncode(description) : "") + (BaseUtil.isNotBlank(nickName) ? "&nickName=" + UnicodeUtil.unicodeEncode(nickName) : "") + (BaseUtil.isNotBlank(name) ? "&name=" + UnicodeUtil.unicodeEncode(name) : "") + (BaseUtil.isNotBlank(mobile) ? "&mobile=" + mobile : "") + (BaseUtil.isNotBlank(unionId) ? "&unionId=" + unionId : "") + (BaseUtil.isNotBlank(avatar) ? "&avatar=" + UnicodeUtil.unicodeEncode(avatar) : ""));

        if (map.get("code").equals(Constant.CHECK_STATUS_DEFAULT)) loadCacheData();

        return map;
    }

    @Override
    public Map<String, Object> deleteById(HttpServletRequest request, Integer id) {
        LogInfoServiceImpl.saveLogInfo(request, "删除用户信息，ID：" + id);

        return HttpRequestUtil.getCompleteData(UserApiUrls.base_prefix + UserApiUrls.delete, "id=" + id);
    }

    @Override
    public Map<String, Object> batchDel(HttpServletRequest request, String ids) {
        LogInfoServiceImpl.saveLogInfo(request, "批量删除用户信息，IDS：" + ids);

        return HttpRequestUtil.getCompleteData(UserApiUrls.base_prefix + UserApiUrls.batchDel, "ids=" + ids);
    }

    @Override
    public Map<String, Object> changeRelation(HttpServletRequest request, Integer alarmRuleId, Integer userId, Integer flag) {
        LogInfoServiceImpl.saveLogInfo(request, "修改用户告警规则关联信息，告警规则ID：" + alarmRuleId + "，用户ID：" + userId + "，状态：" + flag);

        return HttpRequestUtil.getCompleteData(AlarmRuleApiUrls.base_prefix + AlarmRuleApiUrls.changeRelation, "alarmRuleId=" + alarmRuleId + "&userId=" + userId + "&type=" + (null == flag || flag.equals(Constant.CHECK_STATUS_DEFAULT) ? Constant.CHECK_STATUS_SUCCESS : Constant.CHECK_STATUS_DEFAULT));
    }

    @Override
    public List<BaseVo> findListByCompanyId(Integer companyId) {
        List<BaseVo> list = new ArrayList<>();
        Map<String, Object> map;

        for (Object o : HttpRequestUtil.getListData(DeviceApiUrls.base_prefix + DeviceApiUrls.findUserListByCompanyId, "companyId=" + companyId)) {
            map = JsonUtil.json2Map(o);

            if (map.containsKey("id")) list.add(new BaseVo(Integer.parseInt(map.get("id") + ""), map.get("name") + ""));
        }

        return list;
    }

    @Override
    public List<BaseVo> findBaseList() {
        List<BaseVo> list = new ArrayList<>();

        for (Map<String, Object> map : UserServiceImpl.findUserList(null))
            list.add(new BaseVo(Integer.parseInt(map.get("id") + ""), map.get("name") + "（" + (BaseUtil.isBlank(map.get("description") + "") ? map.get("nickName") : map.get("description")) + "）"));

        return list;
    }

    @Override
    public List<Integer> findUserListWithCompanyUser(Integer companyId) {
        List<Integer> list = new ArrayList<>();

        for (Object o : HttpRequestUtil.getListData(UserApiUrls.base_prefix + UserApiUrls.findUserListByCompanyId, "companyId=" + companyId))
            list.add(Integer.parseInt(JsonUtil.json2Map(o).get("id") + ""));

        return list;
    }

    @Override
    public Map<String, Object> syncData(HttpServletRequest request) {
        LogInfoServiceImpl.saveLogInfo(request, "同步用户信息");

        if (CommonsController.needSync("user")) {
            return HttpRequestUtil.getSyncData(3);
        } else {
            return BaseUtil.defaultErrorInfo(null);
        }
    }

    @Override
    public Map<String, Object> updateDeviceUser(HttpServletRequest request, String deviceCode, Integer userId, Integer type, Integer flag) {
        LogInfoServiceImpl.saveLogInfo(request, "修改用户设备关联信息，设备编码：" + deviceCode + "，用户ID：" + userId + "，类型：" + type + "，状态：" + flag);

        return HttpRequestUtil.getCompleteData(DeviceUserApiUrls.base_prefix + DeviceUserApiUrls.updateDeviceUser, "deviceCode=" + deviceCode + "&userId=" + userId + "&type=" + type + "&flag=" + flag);
    }

    @Override
    public Map<String, Object> completeInfo(HttpServletRequest request, String openId, String userName, String companyName, String userMobile) {
        Map<String, Object> map = HttpRequestUtil.getCompleteData(UserApiUrls.base_prefix + UserApiUrls.completeInfo, "openId=" + openId + "&name=" + UnicodeUtil.unicodeEncode(userName) + "&mobile=" + UnicodeUtil.unicodeEncode(userMobile) + "&description=" + UnicodeUtil.unicodeEncode(companyName));

        if (map.get("code").equals(Constant.CHECK_STATUS_DEFAULT)) loadCacheData();

        return map;
    }

    @Override
    public WxUser getWxUserInfoByCode(String code) {
        WxUser wxUser = new WxUser();

        if (BaseUtil.isBlank(code)) return wxUser;

        Map<String, Object> map = HttpRequestUtil.getOnlyData(WechatApiUrls.base_prefix + WechatApiUrls.getWxUserInfoByCode, "code=" + code);

        if (map.containsKey("openId")) {
            wxUser.setOpenId(map.get("openId") + "");
            wxUser.setNickname(map.get("nickname") + "");
            wxUser.setSex(Integer.parseInt(map.get("sex") + ""));
            wxUser.setHeadImgUrl(map.get("headImgUrl") + "");
            if (map.containsKey("unionId")) wxUser.setUnionId(map.get("unionId") + "");

            // 获取用户补充信息
            map = HttpRequestUtil.getOnlyData(UserApiUrls.base_prefix + UserApiUrls.getInfoByOpenId, "openId=" + wxUser.getOpenId());

            if (map.containsKey("id")) {
                wxUser.setId(Integer.parseInt(map.get("id") + ""));
                wxUser.setName(map.get("name") + "");
                wxUser.setMobile(map.get("mobile") + "");
                wxUser.setDescription(map.get("description") + "");
            }
        }

        return wxUser;
    }

    @Override
    public Map<String, Object> userSubscribe(String openId, Boolean isAdd) {
        Map<String, Object> map = HttpRequestUtil.getCompleteData(UserApiUrls.base_prefix + UserApiUrls.userSubscribe, "openId=" + openId + "&isAdd=" + (isAdd ? 1 : 0));

        if (map.get("code").equals(Constant.CHECK_STATUS_DEFAULT)) loadCacheData();

        return map;
    }

    @Override
    public void loadCacheData() {
        CommonsController.baseUserList.clear();

        for (Object o : HttpRequestUtil.getListData(UserApiUrls.base_prefix + UserApiUrls.list, ""))
            CommonsController.baseUserList.add(JsonUtil.json2Map(o));

        if (CommonsController.baseUserList.size() <= 1) {
            try {
                log.info("用户信息请求失败，3秒后自动重试...");

                Thread.sleep(3000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            loadCacheData();
        }

        log.info("共计加载" + CommonsController.baseUserList.size() + "条用户信息...");
    }

    public static List<Map<String, Object>> findUserList(Object companyId) {
        Map<String, Object> userMap = HttpRequestUtil.getOnlyData(UserApiUrls.base_prefix + UserApiUrls.page, "pageNum=1&pageSize=1000000" + (null != companyId && Integer.parseInt(companyId + "") > 0 ? "&companyId=" + companyId : ""));
        List<Map<String, Object>> baseUserMapList = new ArrayList<>();

        if (userMap.containsKey("content")) for (Object content : JSONArray.fromObject(userMap.get("content")))
            baseUserMapList.add(JsonUtil.json2Map(content));

        return baseUserMapList;
    }

    String getCompanyName(Object userId) {
        StringBuilder companyName = new StringBuilder();
        Map<String, Object> companyMap;
        StringBuilder str = new StringBuilder("@");

        for (Object obj : HttpRequestUtil.getListData(DeviceApiUrls.base_prefix + DeviceApiUrls.findCompanyListByUserId, "userId=" + userId)) {
            companyMap = JsonUtil.json2Map(obj);

            if (companyMap.size() > 0 && companyMap.containsKey("name") && !companyName.toString().contains(companyMap.get("name") + "")) {
                companyName.append(companyMap.get("name")).append(",");

                str.append(companyMap.get("id")).append("@");
            }
        }

        if (companyName.toString().length() > 2) {
            UserController.tempUserCompanyMap.put(userId + "", str.toString());

            return companyName.substring(0, companyName.length() - 1);
        } else {
            UserController.tempUserCompanyMap.remove(userId + "");

            return "";
        }
    }
}
